/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import java.util.Vector;
import Logica.Cliente;
import Logica.Ficheiro;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
 *
 * @author Rui Margarido
 */
public class ClientePrincipal extends javax.swing.JFrame 
{
    public static final int MAX_SIZE = 4000;
    JFileChooser fc = new JFileChooser();
    /**
     * Creates new form ClientePrincipal
     */
    public void CarregaLista()
    {
        Vector <String> lista = new Vector<String>();
        
        for(Ficheiro f : Cliente.file)
        {
         //if (f.file.isFile()) {
                lista.add(f.file.getName() + "  /  " + f.getSize() + "  /  " + f.getDataCriacao()+ "  /  " + f.getNumReplicas());
         //}
         //System.out.println(f.file.getName() + " / " + f.getSize() + " / " + f.getDataCriacao() + " / " + f.getNumReplicas());
        }

        ListFicheiros.setListData(lista);
        ListFicheiros.repaint();
        ListFicheiros.revalidate();
    }
    
    public ClientePrincipal() {
        initComponents();
        CarregaLista();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        ListFicheiros = new javax.swing.JList();
        BotaoUpload = new javax.swing.JButton();
        BotaoDownload = new javax.swing.JButton();
        BotaoEliminar = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        ListFicheiros.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(ListFicheiros);

        BotaoUpload.setText("Upload");
        BotaoUpload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotaoUploadActionPerformed(evt);
            }
        });

        BotaoDownload.setText("Download");
        BotaoDownload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotaoDownloadActionPerformed(evt);
            }
        });

        BotaoEliminar.setText("Eliminar");
        BotaoEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotaoEliminarActionPerformed(evt);
            }
        });

        jButton4.setText("Sair");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel1.setText("Nome/Tamanho/Data/Replicas Existentes");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(41, 41, 41)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(BotaoDownload)
                            .addGap(48, 48, 48)
                            .addComponent(BotaoUpload)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(BotaoEliminar)
                            .addGap(53, 53, 53)
                            .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(41, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BotaoDownload)
                    .addComponent(BotaoUpload)
                    .addComponent(BotaoEliminar)
                    .addComponent(jButton4))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        PrintStream envia = null;
        BufferedReader recebe = null;

        try {
            envia = new PrintStream(Cliente.cs.getOutputStream());
            envia.println("4");
        } catch (IOException ex) {
            Logger.getLogger(ClientePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.exit(0);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void BotaoUploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotaoUploadActionPerformed
        PrintStream envia = null;
        BufferedReader recebe = null;
        File file = null;
        Socket sock = null;
        String ip;
        String porto;
        int opcaoSelecionada;
        opcaoSelecionada = fc.showOpenDialog(this);
        
        if(opcaoSelecionada == JFileChooser.APPROVE_OPTION)
        {
            try {
                file = fc.getSelectedFile();
                String nome = file.getName();
                String path = file.getCanonicalPath();
                
                boolean jaExiste=false;
                for( Ficheiro f : Cliente.file )
                    if( nome.equals(f.getNome()))
                        jaExiste=true;
                
                
                if( jaExiste )
                {
                    JOptionPane.showMessageDialog(null,"Ficheiro já existente");
                }
                else
                {
                    try {
                        envia = new PrintStream(Cliente.cs.getOutputStream());
                        envia.println("2");
                        envia.flush();
                    } catch (IOException ex) {
                        Logger.getLogger(ClientePrincipal.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    envia.println(nome);
                    envia.flush();
                    try {
                        recebe = new BufferedReader(new InputStreamReader(Cliente.cs.getInputStream()));
                        ip = recebe.readLine();
                        porto = recebe.readLine();
                        Thread.sleep(100);
                        sock = new Socket(InetAddress.getByName(ip),Integer.parseInt(porto));
                        Thread.sleep(200);
                        upload(sock,nome,path);
                    } catch (IOException ex) {
                        JOptionPane.showMessageDialog(null,"Ficheiro já existente");
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ClientePrincipal.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                
                
            } catch (IOException ex) {
                Logger.getLogger(ClientePrincipal.class.getName()).log(Level.SEVERE, null, ex);
            } 
        }
    }//GEN-LAST:event_BotaoUploadActionPerformed

    private void BotaoDownloadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotaoDownloadActionPerformed
        PrintStream envia = null;
        BufferedReader recebe = null;
        File file;
        Socket sock = null;
        String ip = "";
        String porto = "";
        String nome = "";
        int index;
        index = ListFicheiros.getSelectedIndex();
        if(index != -1)
        {
            try {
                nome = Cliente.file.get(index).getNome();
                System.out.println(nome);
                envia = new PrintStream(Cliente.cs.getOutputStream());
                envia.println("1");
                envia.flush();
            } catch (IOException ex) {
                Logger.getLogger(ClientePrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }

                //JOptionPane.showMessageDialog(null, nome);
                envia.println(nome);
                envia.flush();
                try {
                    recebe = new BufferedReader(new InputStreamReader(Cliente.cs.getInputStream()));   
                    ip = recebe.readLine();
                    porto = recebe.readLine();
                    Thread.sleep(200);
                    sock = new Socket(InetAddress.getByName(ip),Integer.parseInt(porto));
                    Thread.sleep(200);
                    download(sock,nome);
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(null,"Ficheiro já existente");
                } catch (InterruptedException ex) {
                    Logger.getLogger(ClientePrincipal.class.getName()).log(Level.SEVERE, null, ex);
                }
        }
        
    }//GEN-LAST:event_BotaoDownloadActionPerformed

    private void BotaoEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotaoEliminarActionPerformed
        if(Cliente.file.size() != 0)
        {
            PrintStream envia = null;
            BufferedReader recebe = null;
            String nome = "";
            int index;
            index = ListFicheiros.getSelectedIndex();
            if(index != -1)
            {
                nome = Cliente.file.get(index).getNome();
                JOptionPane.showMessageDialog(null, nome);
                try {
                    envia = new PrintStream(Cliente.cs.getOutputStream());
                    envia.println("3");
                    envia.flush();
                } catch (IOException ex) {
                    Logger.getLogger(ClientePrincipal.class.getName()).log(Level.SEVERE, null, ex);
                }

                envia.println(nome);
                envia.flush();
            }
        }
    }//GEN-LAST:event_BotaoEliminarActionPerformed

    public void download(Socket sock, String fileName)
    {
        File file = new File(Cliente.localDirectory + File.separator + fileName);
        file.getParentFile().mkdirs();

        byte[] fileChunck = new byte[MAX_SIZE];
        int nbytes;
        InputStream in = null;
        FileOutputStream localFileOutputStream = null;

        try {
            in = sock.getInputStream();
            String filep = Cliente.localDirectory + File.separator + fileName;
            localFileOutputStream = new FileOutputStream(filep);

        
            while ((nbytes = in.read(fileChunck)) > 0) {
                //System.out.println("Recebido o bloco n. " + ++contador + " com " + nbytes + " bytes.");
                localFileOutputStream.write(fileChunck, 0, nbytes);
                System.out.println("Acrescentados " + nbytes + " bytes ao ficheiro " + fileName + ".");                    
            }

            System.out.println("Transferencia concluida.");
        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    localFileOutputStream.close();
                    //pout.close();
                    if(in != null)
                        in.close();
                } catch (IOException ex) {
                    Logger.getLogger(ClientePrincipal.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    }

   
    
    public void upload(Socket sock, String fileName, String filePath)
    {
        byte []fileChunck = new byte[MAX_SIZE];
        int nbytes;       
        OutputStream out = null;
        FileInputStream SendInputStream = null;
        
        try{
            System.out.println("nome ficheiro: " + fileName );
            System.out.println("caminho ficheiro: " + filePath );
            SendInputStream = new FileInputStream(filePath);
            
            out = sock.getOutputStream();
         
            while((nbytes = SendInputStream.read(fileChunck))>0)
            {                        
                out.write(fileChunck, 0, nbytes);
                out.flush();      
                System.out.println("NBYtes:   "+nbytes);
            }    
            System.out.println("Envio concluido com sucesso.");
        } catch (IOException ex) {
            Logger.getLogger(ClientePrincipal.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                out.close();
                SendInputStream.close();
            } catch (IOException ex) {  
                Logger.getLogger(ClientePrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    
    /**
     * @param args the command line arguments
     */
  
   // public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
  /*      try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientePrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientePrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientePrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientePrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
*/
        /* Create and display the form */
    /*    java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClientePrincipal().setVisible(true);
            }
        });
    }*/

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BotaoDownload;
    private javax.swing.JButton BotaoEliminar;
    private javax.swing.JButton BotaoUpload;
    private javax.swing.JList ListFicheiros;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
